/**
 * \ * JAVACC DEMO 1.0
 */
package com.apache.portal.thread;

import com.apache.api.vo.ResultEntity;
import com.apache.client.DictCoreClient;
import com.apache.database.model.Page;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  定时获取数据字典信息
 *
 * @author Hou Dayu 创建时间：2016-12-29
 */
public class CreateDictInfoSchedulerJob implements ISchedulerJob {

    private Logger log = Logger.getLogger(CreateDictInfoSchedulerJob.class);

    private static transient boolean CreateDictInfoTaskMark = true;//线程执行标志

    public CreateDictInfoSchedulerJob() {
    }

    public void run() {
        try {
            if (CreateDictInfoTaskMark) {
                CreateDictInfoTaskMark = false;
                log.info("定时从【基础平台】服务端初始化加载数据字典信息start....");
                //2）加载【省市地区】
                createCityDict("area");

                //专利的 IPC分类（三级结构，利用createCityDict查询和封装数据）
                //createCityDict("ipc");

                //3）加载常用的数据字典
                createCommonDictSelectDataFile();

                log.info("定时从【基础平台】服务端初始化加载数据字典信息end....");
                CreateDictInfoTaskMark = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CreateDictInfoTaskMark = true;
        }
    }

    /**
     * 加载【省市地区、和其他多层级级联数据（如专利IPC分类等）】
     */
    private void createCityDict(String cateEname) {
        String jsFileName1 = "jquery.cityselect-dict-data.js";
        if ("area".equals(cateEname)) {
            jsFileName1 = "jquery.cityselect-dict-data.js";
        } else {
            jsFileName1 = "jquery.select-dict-data-" + cateEname + ".js";
        }
        Map<String, Object> dataMap1 = new HashMap<String, Object>();
        dataMap1.put("cateEname", cateEname);
        dataMap1.put("fatherValue", "0");
        log.info("加载【" + cateEname + "】文件【" + jsFileName1 + "】 ，本次请求参数=" + dataMap1);
        Map result1 = DictCoreClient.getInstance().dictCityInfo(dataMap1);
        if (null == result1) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            result1 = DictCoreClient.getInstance().dictCityInfo(dataMap1);
            if (null == result1) {
                JSONObject array = JSONObject.fromObject("{}");
                log.info("未获取到[area]数据=" + array.toString());
                return;
            }
        }
        JSONObject array = JSONObject.fromObject(result1);
        log.info("获取[area]的数据=" + result1);
        newFile(array.toString(), jsFileName1);
    }

    /**
     * 加载【常用的数据字典】
     */
    private void createCommonDictSelectDataFile() {
        Map<String, String> dictFileMap = new HashMap<String, String>();
        dictFileMap.put("area", "省市地区");

        //		dictFileMap.put("hyfl", "行业分类");
        //		dictFileMap.put("qualityLevel", "质量等级");
        //		dictFileMap.put("categoryType", "品种分类");
        //		dictFileMap.put("productUnit", "单位");
        //		dictFileMap.put("proStatus", "商品状态");
        //		dictFileMap.put("userType", "用户类型");
        //		dictFileMap.put("lcType", "理财收益类型");
        //
        //		//加载：客户注册、审核数据字典
        //		dictFileMap.put("Industrycode", "所属行业");
        //		dictFileMap.put("buyerjjlx", "企业类型");
        //		dictFileMap.put("memberType", "会员类型");
        //		dictFileMap.put("legalPerson", "法人性质");
        //		dictFileMap.put("pCertifType", "个人证件类型-个人-法人-经办人");
        //		dictFileMap.put("oCertifType", "企业证件类型");
        //		dictFileMap.put("intelligence", "资质证书类型");
        //		dictFileMap.put("userGraduate", "用户类型企业-个人");
        //		dictFileMap.put("userStatus", "用户状态");
        //		dictFileMap.put("industry", "所属行业");
        //		dictFileMap.put("industryZchl", "行业分类");
        //		dictFileMap.put("dealWay", "交易/成交方式");
        //		dictFileMap.put("nytCateType", "农e通品种分类");
        //		dictFileMap.put("zjsSbtype", "中技所-商标分类");

        //加载全部数据库字典对应cateEname
        addDictFileMap(dictFileMap, "");
        if (dictFileMap.containsKey("userstatus")) {

            System.out.println(dictFileMap.get("userstatus"));
        }
        //开始遍历：
        int i = 0;
        for (Map.Entry<String, String> et : dictFileMap.entrySet()) {
            i++;
            String cateEname = et.getKey();
            String cateTextName = et.getValue();
            if (cateEname.equals("userstatus")) {
                System.out.println(cateTextName);
            }
            String fileName = "dict-data-" + cateEname.toLowerCase() + ".js";

            Map<String, Object> dataMap2 = new HashMap<String, Object>();
            dataMap2.put("cateEname", cateEname);
            dataMap2.put("fatherValue", "0");
            ResultEntity result2 = DictCoreClient.getInstance().dictSelect(dataMap2);
            if (null == result2 || !"true".equals(result2.getResult())) {
                JSONObject array = JSONObject.fromObject("{}");
                log.info("数据字典[" + i + "]加载[" + cateEname + "-" + cateTextName + "]数据异常=" + array
                        .toString());
            } else {
                String enstr = String.valueOf(result2.getEntity());
                log.info("数据字典[" + i + "]加载[" + cateEname + "-" + cateTextName + "]数据完成=" + enstr);
                newFile(enstr, fileName);
            }
        }
    }

    /**
     * 按系统级别添加Map的cateEname
     *
     * @param dictFileMap
     * @param sysName
     */
    private void addDictFileMap(Map<String, String> dictFileMap, String sysName) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("doCode", "dictCateList");
        if (StrUtil.isNotNull(sysName)) {
            paramsMap.put("sysEname", sysName);
        }
        paramsMap.put("sysPass", ConfigUtil.getInstance().interfacePass());

        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("dictService", "dictList", paramsMap,
                        PortalPubFactory.getInstance().getRpcInfo("dict"));
        //以后在put累加（网站需要生成js的数据字典）
        if (null == entity.getEntity()) {
            log.info("获取失败：" + entity.getMessage());
        } else {
            List list = new ArrayList();
            if (entity.getEntity() instanceof Page) {
                Page page = (Page) entity.getEntity();
                list = page.getPageObjects();
            } else {
                list = (List) entity.getEntity();
            }
            for (Object object : list) {
                JSONObject js = JSONObject.fromObject(object);
                //				System.out.println(js.getString("cateEname"));
                dictFileMap.put(js.getString("cateEname"),
                        js.getString("cateCname") + "-" + js.getString("sysEname"));
            }
        }
    }

    /**
     * 重新写文件
     *
     * @param fileContent 文件内容
     * @param fileName 生成的js文件名称
     */
    private void newFile(String fileContent, String fileName) {
        File filePath = new File(
                ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "") + "js/dictData/"
                        + fileName);
        FileOutputStream fo = null;
        OutputStreamWriter osw = null;
        PrintWriter out1 = null;
        try {
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            log.info("存储数据至：" + filePath.getPath());

            fo = new FileOutputStream(filePath);
            osw = new OutputStreamWriter(fo, "UTF-8");
            out1 = new PrintWriter(osw);
            out1.println(fileContent);
            out1.close();
            osw.close();
            fo.close();
        } catch (Exception e) {
            log.error("操作文件[" + filePath.getPath() + "]出错ERROR KEY:" + e.getMessage());
        } finally {
            IOUtils.closeQuietly(out1);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(fo);
        }
    }
}
